package com.lingjtx.im.core.handle;

import com.lingjtx.common.redis.config.SnowflakeConfig;
import com.lingjtx.common.redis.service.IRedisService;
import com.lingjtx.im.core.common.ChannelPool;
import com.lingjtx.im.core.common.SessionManager;
import com.lingjtx.im.core.distribute.MessagePublisher;
import com.lingjtx.im.core.protocol.MessageProto;
import com.lingjtx.im.core.protocol.ProtocolWrapper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@ChannelHandler.Sharable
@Component
public class WebSocketHandler extends SimpleChannelInboundHandler<ProtocolWrapper> {

    private final IRedisService redisService;

    private final MessagePublisher publisher;

    private final SnowflakeConfig snowflakeConfig;

    public WebSocketHandler(IRedisService redisService, MessagePublisher publisher, SnowflakeConfig snowflakeConfig) {
        this.redisService = redisService;
        this.publisher = publisher;
        this.snowflakeConfig = snowflakeConfig;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolWrapper wrapper) throws Exception {

        MessageProto.IMMessage message = MessageProto.IMMessage.newBuilder(wrapper.getMessage())
                .setMsgId(String.valueOf(snowflakeConfig.nextId()))
                .setTimestamp(System.currentTimeMillis())
                .setSenderId(ChannelPool.getUserId(ctx.channel())).build();

        publisher.publish(ProtocolWrapper.of(wrapper.getImType(), message));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Websocket connected!");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionManager.removeSession(ctx.channel(), redisService);
        log.info("Websocket disconnected! userId: {}", ChannelPool.getUserId(ctx.channel()));
    }
}
